<?php

namespace app\admin\controller;
require_once '../vendor/qiniu/php-sdk/autoload.php';

use think\Controller;
use think\Db;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Config as QiniuConfig;
use Qiniu\Storage\UploadManager;
use think\facade\Config;
use think\facade\Request;

class Qiniu extends Base
{
    protected $config = [
        'bucket' => '',
        'accessKey' => '',
        'secretKey' => ''
    ];
    // 实例化并传入参数
    public function __construct()
    {
        $this->config['bucket'] = config('param.bucket');
        $this->config['accesskey'] = config('param.accesskey');
        $this->config['secretkey'] = config('param.secretkey');
    }

    public function gettoken()
    {
        $auth = new Auth($this->config['accesskey'], $this->config['secretkey']);
        $upToken = $auth->uploadToken($this->config['bucket']);
        // $data['']
        if ($upToken) {
            $subDomain = Request::subDomain();
            if ($subDomain == 'weiweipan') {
                $subDomain='www';
            }else{
                $subDomain==''?'www':$subDomain;
            }

            $data['uptoken'] = $upToken;
            $data['path'] = $subDomain.'/f' . session('uid') . time() . '/';
            $data['downloadurl'] = url('downloadurl');
            $data['msg'] = '获取成功';
            $data['code'] = 0;
        } else {
            $data['msg'] = '获取失败';
            $data['code'] = 1;
        }
        return json($data);
    }

    public function downloadurl()
    {
        $auth = new Auth($this->config['accesskey'], $this->config['secretkey']);
        $baseUrl = 'https://file.weibuyun.com/' . input('file');
        $this->redirect($auth->privateDownloadUrl($baseUrl,300), 302);
    }
    public function delqiniu($file){
        $file=str_replace('/qiniu/downloadurl?file=',"",$file);
        $auth = new Auth($this->config['accesskey'], $this->config['secretkey']);
        $config = new QiniuConfig();
        $bucketManager = new BucketManager($auth, $config);
       return $err = $bucketManager->delete($this->config['bucket'], $file);
    }
}